package com.liankuan.console.exception;

import com.liankuan.console.common.BaseRsp;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author **
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ServiceException.class)
    public @ResponseBody
    BaseRsp handleBusinessException(Exception ex) {
        if (ex instanceof ServiceException) {
            return new BaseRsp(((ServiceException) ex).getErrorCode(), ex.getMessage());
        }
        return null;
    }

    @ExceptionHandler(BindException.class)
    public @ResponseBody
    BaseRsp handleBindException(BindException ex) {
        StringBuilder sb = new StringBuilder();
        for (FieldError fieldError : ex.getFieldErrors()) {
            sb.append(fieldError.getDefaultMessage());
        }
        return new BaseRsp(400, sb.toString());
    }

    /**
     * 全局异常处理器，线上环境使用
     */
    @ExceptionHandler(Exception.class)
    public @ResponseBody
    BaseRsp handleException(Exception ex) {
        ex.printStackTrace();
        return new BaseRsp(500, "服务器开小差了，请稍等哦~~");
    }
}
